package com.ada.skill;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class SeckillService {
    private final ConcurrentHashMap<Long, AtomicInteger> inventory = new ConcurrentHashMap<>();

    public SeckillService() {
        // 初始化商品库存
        inventory.put(1L, new AtomicInteger(100)); // 商品ID为1，初始库存为100
    }

    public boolean seckill(long productId) {
        AtomicInteger stock = inventory.get(productId);

        if (stock != null && stock.get() > 0) {
            // 检查库存是否充足
            int remaining = stock.decrementAndGet();
            if (remaining >= 0) {
                // 执行秒杀逻辑，可以是下订单等操作
                System.out.println("秒杀成功，商品ID：" + productId);
                return true;
            } else {
                // 库存不足，需要还原
                stock.incrementAndGet();
                System.out.println("秒杀失败，商品ID：" + productId + " 库存不足");
                return false;
            }
        } else {
            // 商品不存在或库存不足
            System.out.println("秒杀失败，商品ID：" + productId + " 不存在或库存不足");
            return false;
        }
    }

    public static void main(String[] args) {
        SeckillService seckillService = new SeckillService();

        // 模拟多线程并发秒杀请求
        for (int i = 0; i < 200; i++) {
            final int threadId = i;
            new Thread(() -> {
                boolean success = seckillService.seckill(1L); // 商品ID为1
                if (success) {
                    System.out.println("Thread " + threadId + " 秒杀成功");
                } else {
                    System.out.println("Thread " + threadId + " 秒杀失败");
                }
            }).start();
        }
    }
}
